<template>
  <div class="login-container">
    <!-- 登录表单 -->
    <!-- v-loading.lock.lock="loading" -->
    <div class="login-form-container">
      <div class="icon">
        <el-icon><TakeawayBox /></el-icon>
      </div>
      <!-- 使用账号密码登录 -->
      <div class="account-login" v-if="loginMode === 'account'">
        <!-- 账号 -->
        <div class="account">
          <el-input placeholder="请输入账号" v-model="account" clearable :prefix-icon="Avatar"> </el-input>
        </div>
        <!-- 密码 -->
        <div class="password">
          <el-input placeholder="请输入密码" v-model="password" :show-password="true" :prefix-icon="Lock"> </el-input>
        </div>
      </div>
      <!-- 使用手机号验证码登录 -->
      <div class="phone-login" v-else>
        <!-- 账号 -->
        <div class="phone">
          <el-input placeholder="请输入手机号" v-model="phone" clearable :maxlength="11" :minlength="11" :prefix-icon="PhoneFilled">
            <template #append>
              <el-button v-if="canGetCode" @click="getCode" type="primary">获取验证码</el-button>
              <el-button v-else disabled>{{ time }}s重新获取</el-button>
            </template>
          </el-input>
        </div>
        <!-- 密码 -->
        <div class="code">
          <el-input placeholder="请输入验证码" v-model="code" clearable :prefix-icon="Key" maxlength="6" minlength="6" />
        </div>
      </div>
      <!-- 登录按钮 -->
      <div class="login-btn">
        <el-button type="primary" @click="login" :loading="loading">登录</el-button>
        <el-button type="primary" @click="toggleLoginMode" v-if="loginMode == 'account'">手机号登录</el-button>
        <el-button type="primary" @click="toggleLoginMode" v-else>账号登录</el-button>
      </div>
      <!-- 注册账号和忘记密码 -->
      <div class="register-forget">
        <div class="register" @click="centerDialogVisible = true">注册账号</div>
        <div class="forget" @click="centerDialogVisibleForget = true">忘记密码？</div>
      </div>
    </div>
    <!-- 背景图 -->
    <img src="../../../public/img/login_center_bg.5307896.png" alt="" />

    <!-- 忘记密码 -->
    <el-dialog title="忘记密码" v-model="centerDialogVisibleForget" width="500px" center>
      <Forget @hide-forget="centerDialogVisibleForget = false"></Forget>
    </el-dialog>

    <!-- 注册账号 -->
    <el-dialog title="注册" v-model="centerDialogVisible" width="500px" center draggable>
      <Register @hide-register="centerDialogVisible = false"></Register>
    </el-dialog>
  </div>
</template>

<script setup>
import Forget from './Forget.vue'
import Register from './Register.vue'
import { ElMessage } from 'element-plus'
import axios from '../../utils/request'
import { useRouter } from 'vue-router'
import { TakeawayBox, Avatar, Lock, Key, PhoneFilled } from '@element-plus/icons-vue'
import { ref } from 'vue'
let loginMode = ref('account') // 登录模式，账号登录，手机号登录
let loading = ref(false) // 是否加载中
let account = ref('') // 登录账号
let password = ref('') // 登录密码
let phone = ref('') // 手机号
let code = ref('') // 验证码
let time = ref(60) // 发送验证后的计时器
let canGetCode = ref(true)
let centerDialogVisible = ref(false)
let centerDialogVisibleForget = ref(false)

// 创建路由对象
const router = useRouter()

// 切换登录模式
const toggleLoginMode = () => {
  account.value = ''
  password.value = ''
  phone.value = ''
  code.value = ''
  if (loginMode.value === 'account') {
    loginMode.value = 'phone'
  } else {
    loginMode.value = 'account'
  }
}
// 获取验证码
const getCode = async () => {
  // 手机号不能为空
  if (!phone.value) {
    return ElMessage({
      message: '请输入手机号！',
      type: 'error'
    })
  }
  // 手机号必须满足验证规则
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    return ElMessage({
      message: '手机号格式错误！',
      type: 'error'
    })
  }
  // 显示加载状态
  loading.value = true
  // 发起请求获取验证码
  try {
    const data = await axios.post('/api/getcode', {
      phone: phone.value
    })

    // 获取成功
    if (data.code === 0) {
      canGetCode.value = false
      ElMessage({
        message: '验证码发送成功，请注意查收！',
        type: 'success'
      })
      const timer = setInterval(() => {
        time.value--
        if (time.value <= 0) {
          clearInterval(timer)
          time.value = 60
          canGetCode.value = true
        }
      }, 1000)
    } else {
      ElMessage.error(data.msg)
    }
  } catch (err) {
    ElMessage.error(err)
  } finally {
    loading.value = false
  }
}

// 登录接口处理函数
const login = async () => {
  // 使用账号密码登录
  let data
  if (loginMode.value === 'account') {
    // 验证账号不能为空
    if (account.value === '') {
      return ElMessage.error('账号不能为空！')
    }
    // 账号长度在1-64之间
    if (!(account.value.length >= 1 && account.value.length <= 64)) {
      return ElMessage.error('账号长度在1-64之间!')
    }
    // 密码不能为空
    if (password.value === '') {
      return ElMessage.error('密码不能为空！')
    }
    // 密码必须包含字母和数字
    if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(password.value)) {
      return ElMessage.error('密码必须包含字母数字组合，且长度为6-16位！')
    }
    loading.value = true
    // 发起登录请求
    try {
      data = await axios.post('/api/bus/login', {
        name: account.value,
        password: password.value
      })
    } catch (err) {
      ElMessage.error(err)
    } finally {
      loading.value = false
    }
  } else {
    // 手机号不能为空
    if (!phone.value) {
      return ElMessage.error('请输入手机号！')
    }
    // 手机号必须满足验证规则
    if (!/^1[3-9]\d{9}$/.test(phone.value)) {
      return ElMessage.error('手机号格式错误！')
    }
    // 验证码不能为空
    if (code.value === '') {
      return ElMessage.error('验证码不能为空！')
    }
    // 验证码位6位有效数字
    if (!/\d{6}/.test(code.value)) {
      return ElMessage.error('验证码位6位有效数字！')
    }
    loading.value = true
    // 使用手机验证码登录
    try {
      data = await axios.post('/api/bus/login', {
        phone: phone.value,
        code: code.value
      })
    } catch (err) {
      ElMessage.error(err)
    } finally {
      loading.value = false
    }
  }
  // // 登录成功，将后台返回得token保存在本地
  if (data.code === 0) {
    localStorage.setItem('bus_token', data.token)
    ElMessage({
      type: 'success',
      message: '登录成功！'
    })
    // 跳转到首页
    router.push('/home')
  } else {
    ElMessage.error('登录失败，' + data.msg)
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  .login-form-container {
    padding: 20px;
    border-top: 10px solid #409eff;
    width: 320px;
    position: absolute;
    left: 0;
    right: 0;
    margin: 140px auto;
    background-color: #fff;
    color: #303133;
    box-shadow: 0 2px 15px #ccc;

    .icon {
      text-align: center;

      .el-icon {
        font-size: 60px;
        color: #409eff;
      }
    }

    .account-login {
      :deep(.el-icon) {
        color: #409eff;
        font-size: 18px;
      }

      .account {
        margin-top: 20px;
      }
      .password {
        margin-top: 30px;
      }
    }

    .phone-login {
      :deep(.el-icon) {
        color: #409eff;
        font-size: 18px;
      }
      :deep(.el-input-group__append) {
        background-color: #409eff;
        color: #fff;
      }

      .phone {
        margin-top: 20px;
      }
      .code {
        margin-top: 30px;
      }
    }

    .login-btn {
      margin-top: 30px;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .el-button {
        width: 140px;
      }
    }

    .register-forget {
      display: flex;
      justify-content: space-between;
      margin-top: 40px;
      padding: 10px 10px 20px;
      .register,
      .forget {
        cursor: pointer;
        font-size: 14px;
      }
    }
  }
  img {
    background: #409eff;
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    margin-top: 200px;
  }
}
</style>
